package com.labs;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 复制文件
 */
public class CopyFiles {
    public static void copyFilesWithThreads(String filePath, File[] listFiles, int threadCount) throws InterruptedException, IOException {
        File logFile = new File(filePath, "处理结果.txt");

        int totalFiles = listFiles.length;;
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        AtomicInteger successCount = new AtomicInteger(0);
        AtomicInteger errorCount = new AtomicInteger(0);
        // System.out.println("使用 " + threadCount + " 个线程移动 " + totalFiles + " 个文件");
        int filesPerThread = totalFiles / threadCount;
        int remainingFiles = totalFiles % threadCount;
        // 使用线程安全的集合来收集错误文件
        ConcurrentLinkedQueue<String> errorFiles = new ConcurrentLinkedQueue<>();
        final int[] dirCount = new int[]{0};

        for(int i = 0; i < threadCount; i++){
            int startIndex = i * filesPerThread;
            int endIndex = startIndex + filesPerThread;
            if(i == threadCount -1){
                endIndex += remainingFiles;
            }

            final int threadId = i;
            final int finalStart = startIndex;
            final int finalEnd = endIndex;
            executor.submit(() -> {
                // System.out.println("线程 " + threadId + " 开始复制文件，范围: " + finalStart + " - " + (finalEnd - 1));
                int threadSuccess = 0;
                int threadError = 0 ;
                List<String> threadErrorList = new ArrayList<>();

                for (int j = finalStart; j < finalEnd; j++) {
                    File file = listFiles[j];
                    if(!file.isFile()){
                        dirCount[0] ++;
                        // 跳过目录
                        continue;
                    }
                    String fileName = file.getName();
                    // System.out.println(fileName);
                    String newFileName = removeChineseKeepExtension(fileName);

                    String prefix = newFileName.split("\\.")[0];
                    File newDir = new File(file.getParent(), prefix);
                    File targetFile = new File(newDir, newFileName);
                    // System.out.println("复制后路径是:"+newDir.getPath());
                    try {
                        if (!newDir.exists()) {
                            newDir.mkdir();
                        }
                        // 复制文件
                        Files.copy(file.toPath(), targetFile.toPath());
                        threadSuccess++;
                    }catch(IOException ioe){
                        threadErrorList.add(fileName);
                        threadError ++;
                        ioe.printStackTrace();
                    }
                }
                successCount.addAndGet(threadSuccess);
                errorCount.addAndGet(threadError);
                errorFiles.addAll(threadErrorList); // 线程安全地添加错误文件
                System.out.println("线程 " + threadId + " 完成: 成功 " + threadSuccess + " 个, 失败 " + threadError + " 个");
            });
        }
        // 关闭线程池并等待所有任务完成
        executor.shutdown();
        boolean finished = executor.awaitTermination(10, TimeUnit.MINUTES);

        if (finished) {
            // System.out.println("\n文件复制完成!");
            try(FileWriter writer = new FileWriter(logFile, true)){
                writer.write("文件路径"+filePath);
                writer.write("\r\n文件复制完成!");
                writer.write("\r\n共有 "+listFiles.length+" 个文件. ");
                writer.write("\r\n其中有目录"+dirCount[0]+"个 ");
                writer.write("\r\n成功复制: " + successCount.get() + " 个文件 \r\n");
                if(errorFiles.size() > 0){
                    writer.write("复制失败: " + errorCount.get() + " 个文件. 文件名是: "+String.join(",", errorFiles));
                }
            }
            // System.out.println("成功复制: " + successCount.get() + " 个文件");
            // System.out.println("复制失败: " + errorCount.get() + " 个文件.文件名是: "+String.join(",", errorFiles));
        } else {
            // System.out.println("任务超时，强制关闭线程池");
            try(FileWriter writer = new FileWriter(logFile, true)){
                writer.write("任务超时，强制关闭线程池");
            }
            executor.shutdownNow();
        }
    }



    /**
     * 删除中文字符并保留扩展名
     */
    private static String removeChineseKeepExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf(".");

        if (lastDotIndex == -1) {
            // 没有扩展名
            return removeChineseWithValidation(fileName);
        }

        String namePart = fileName.substring(0, lastDotIndex);
        String extension = fileName.substring(lastDotIndex);

        String cleanedName = removeChineseWithValidation(namePart);

        cleanedName = cleanedName.replace("SOP-", "SOP-TR-");

        return cleanedName + extension;
    }

    /**
     * 删除中文字符并进行验证
     */
    private static String removeChineseWithValidation(String text) {
        String result = text.replaceAll("[\\u4e00-\\u9fa5]", "");

        if (result.trim().isEmpty()) {
            return "unnamed";
        }

        // 清理多余的特殊字符
        result = result.replaceAll("^[._\\-]+", ""); // 移除开头的特殊字符
        result = result.replaceAll("[._\\-]+$", ""); // 移除结尾的特殊字符
        result = result.replaceAll("[._\\-]{2,}", "-"); // 将连续的特殊字符替换为单个下划线

        return result;
    }
}
